'use client'
import React, {useEffect, useRef, useState} from 'react';
import {Input, Button, Avatar, Tag, Flex} from 'antd';
import {useRouter} from 'next/router';
import http from "../services/http";

let ws;
const ChatPanel = () => {
    const router = useRouter();
    const [selectedUser, setSelectedUser] = useState(null);
    const [inputText, setInputText] = useState('');
    const [chatMessages, setChatMessages] = useState({});
    const [userInfo, setUserInfo] = useState({});
    const queryInfo = router.query;
    const [users, setUsers] = useState([])

    useEffect(() => {
        // 初始化 WebSocket 连接
        ws = new WebSocket('ws://localhost:8090');

        ws.onopen = () => {
            console.log('已连接到 WebSocket 服务器');
            // 注册当前用户
            const registerMessage = {
                type: 'register',
                userId: userInfo.id // 确保 userInfo.id 是有效的用户 ID
            };
            ws.send(JSON.stringify(registerMessage));
            console.log('发送注册消息:', registerMessage);
        };

        ws.onmessage = (event) => {
            console.log('收到消息:', event.data);
            const parsedMsg = JSON.parse(event.data);

            if (parsedMsg.status === 'success') {
                const { chat_id, sender_id, message, timestamp } = parsedMsg;


                setChatMessages(prevMessages => {
                    const updatedMessages = {
                        ...prevMessages,
                        [sender_id]: [...(prevMessages[sender_id] || []), {
                            id: Date.now(),
                            text: message,
                            sender: sender_id === userInfo.id ? 'You' : 'Other',
                            timestamp: new Date().toLocaleTimeString()
                        }]
                    };
                    console.log('Updated chatMessages:', updatedMessages); // 正确地在状态更新回调内部打印
                    return updatedMessages;
                });

            } else {
                console.error('服务器返回错误:', parsedMsg.message);
            }
        };

        ws.onclose = () => {
            console.log('连接已关闭');
        };

        ws.onerror = (error) => {
            console.error('WebSocket 错误:', error);
        };

        return () => {
            if (ws) ws.close();
        };
    }, [userInfo.id]);


    const sendMessage = (e) => {
        e.preventDefault(); // 阻止默认的表单提交行为
        if (!selectedUser || inputText.trim() === '') return;

        // 确保 WebSocket 连接已经打开
        if (ws.readyState !== WebSocket.OPEN) {
            console.error('WebSocket 连接未打开');
            return;
        }

        // 构建消息对象
        const newMessage = {
            type: userInfo.contactRole === 'hr' ? 'hr' : 'worker', // 根据用户角色设置消息类型
            chat_id: Number(queryInfo.workId),
            user_id: userInfo.id, // 当前用户ID，即发送者的ID
            message: inputText, // 消息内容
            timestamp: new Date().toISOString(), // 消息时间戳
            targetUserId: selectedUser // 目标用户ID
        };
        // 通过 WebSocket 发送消息到服务器
        try {
            ws.send(JSON.stringify(newMessage));
            console.log('发送的消息:', newMessage);
        } catch (error) {
            console.error('消息发送失败:', error);
        }

        // 更新本地消息状态
        setChatMessages(prevMessages => ({
            ...prevMessages,
            [selectedUser]: [...(prevMessages[selectedUser] || []), {
                id: Date.now(), // 本地生成唯一的消息ID
                text: inputText,
                sender: 'You', // 当前用户发送的消息
                timestamp: new Date().toLocaleTimeString()
            }]
        }));

        // 清空输入框
        setInputText('');
    };


    useEffect(() => {
        const fetchUserInfo = async () => {
            let data = {
                userId: Number(queryInfo.userId)
            };

            try {
                let response;
                if (queryInfo.contactRole === 'hr') {
                    response = await http.post('/user/getHrInfo', data);
                } else if (queryInfo.contactRole === 'worker') {
                    response = await http.post('/user/getHrInfo', data);
                }

                if (response) {
                    const resData = response.data;
                    const newUser = {
                        id: resData.id,
                        nickname: resData.nickname,
                        avatar: resData.avatar,
                        work_position: resData.work_position
                    };

                    console.log('Fetched user:', newUser);

                    setUsers([newUser]);

                    // 设置默认选中的用户为 URL query 中的用户
                    if (queryInfo.userId) {
                        setSelectedUser(Number(queryInfo.userId));

                        const data ={
                            workId:queryInfo.workId,
                            userId1:userInfo.id,
                            userId2:queryInfo.userId
                        }
                        http.post('/message/getHistoryMsg',data).then((res)=>{

                            let historyMessages = res.data.map(msg => ({
                                id: msg.id,
                                text: msg.message,
                                sender: msg.user_id === userInfo.id ? 'You' : 'Other', // 判断消息发送者
                                timestamp: new Date(msg.timestamp).toLocaleTimeString()
                            }));

                            // 初始化聊天记录
                            setChatMessages(prevMessages => ({
                                ...prevMessages,
                                [Number(queryInfo.userId)]: historyMessages
                            }));
                        })

                    }
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
            }
        };

        fetchUserInfo();

        // 从 localStorage 获取当前用户信息
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        if (userInfo) {
            setUserInfo(userInfo);
        }

    }, [queryInfo.userId, queryInfo.contactRole,queryInfo.workId]);


    return (
        <div className="flex max-h-[700px] h-[700px] bg-slate-100 shadow-xl max-w-[800px] rounded-2xl overflow-auto no-scrollbar">
            <ChatList users={users} selectedUser={selectedUser} onSelectUser={setSelectedUser}/>
            <div className="flex-1 flex flex-col">
                <ChatContent user={selectedUser ? users.find(u => u.id === selectedUser) : null}
                             messages={chatMessages[selectedUser] || []}
                             currentUser={userInfo}/>
                <div className="p-4 flex flex-row">
                    <Input.TextArea
                        rows={2}
                        value={inputText}
                        onChange={e => setInputText(e.target.value)}
                        onPressEnter={sendMessage}
                        placeholder="正在发送消息..."
                        className="mr-2"
                    />
                    <Button type="primary" onClick={sendMessage} disabled={!inputText.trim()} className="mt-4">
                        发送
                    </Button>
                </div>
            </div>
        </div>
    );
};

// 聊天列表组件
const ChatList = ({users, selectedUser, onSelectUser}) => {
    return (
        <div className="w-1/5 overflow-auto border-r border-gray-300 px-4 mt-2">
            {users.map(user => (
                <div key={user.id} onClick={() => onSelectUser(user.id)}
                     className={`my-2 p-2 items-center cursor-pointer ${Number(selectedUser) === Number(user.id) ? 'bg-blue-200 rounded-2xl' : ''}`}>
                    <Avatar src={user.avatar} className="mr-2"/>
                    {user.nickname}
                </div>
            ))}
        </div>
    );
};

// 聊天内容组件
const ChatContent = ({user, messages, currentUser,chatId}) => {
    const router = useRouter();
    const messagesEndRef = useRef(null);

    const scrollToBottom = () => {
        if (messagesEndRef.current) {
            messagesEndRef.current.scrollIntoView({behavior: 'smooth'});
        }
    };

    const goBack = () => {
        // 返回上一个页面，但不添加历史记录
        router.replace('/dept_manage');
    };
    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    return (
        <div className="flex-1 overflow-auto p-2 mt-2 ml-2">
            <Flex className="justify-between sticky top-2 z-10">
                <Flex className="items-center z-10">
                    <h2 className="text-lg font-semibold mr-4">{user ? `正在与 ${user.nickname} 沟通` : '选择一个聊天'}</h2>
                    <Tag color="orange">{user ? user.work_position : ''}</Tag>
                </Flex>
                <div className="mr-4 z-10">
                    <Button type="primary" size="small" onClick={goBack}>返回</Button>
                </div>

            </Flex>

            <div className="space-y-2 mt-4 z-1">
                {messages.map(msg => (
                    <div key={msg.id}
                         className={`flex items-start ${msg.sender === 'You' ? 'flex-row-reverse' : 'flex-row'}`}>
                        <Avatar src={msg.sender === 'You' ? currentUser.avatar : user.avatar} className="mx-2"/>
                        <div
                            className={`p-2 text-sm ${msg.sender === 'You' ? 'bg-green-200' : 'bg-blue-100'} rounded-md max-w-lg break-words`}>
                            <p>{msg.text}</p>
                            <p className="text-xs text-gray-500">{msg.timestamp}</p>
                        </div>
                    </div>
                ))}
                <div ref={messagesEndRef}/>
            </div>
        </div>
    );
};

export default ChatPanel;
